package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.conditions.ProjectsConditions;
import com.ruoyi.system.domain.FileUpload;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.response.ProjectsInfo;
import com.ruoyi.system.service.IFileUploadService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ProjectsMapper;
import com.ruoyi.system.domain.Projects;
import com.ruoyi.system.service.IProjectsService;
import com.ruoyi.common.core.text.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 项目信息Service业务层处理
 *
 * @author tanshen
 * @date 2023-10-07
 */
@Service
public class ProjectsServiceImpl extends ServiceImpl<ProjectsMapper, Projects> implements IProjectsService {
    @Autowired
    private ProjectsMapper projectsMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private IFileUploadService fileUploadService;

    /**
     * 查询项目信息
     *
     * @param id 项目信息主键
     * @return 项目信息
     */
    @Override
    public ProjectsInfo selectProjectsById(Long id) {
        Projects projects = projectsMapper.selectProjectsById(id);
        List<Long> userIds = getTeamMembersUserId(projects.getTeamMembers());
        userIds.add(projects.getOwnerId());
        userIds = userIds.stream().distinct().collect(Collectors.toList());
        List<SysUser> userList = sysUserMapper.selectUserByIds(userIds);
        Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));

        ProjectsInfo projectsInfo = new ProjectsInfo();
        BeanUtils.copyBeanProp(projectsInfo, projects);

        SysUser user = new SysUser();
        user.setUserName(userMap.get(projectsInfo.getOwnerId()));
        user.setUserId(projectsInfo.getOwnerId());
        projectsInfo.setOwner(user);

        List<Long> teamMembers = getTeamMembersUserId(projects.getTeamMembers());
        List<SysUser> users = new ArrayList<>();
        for (Long userId : teamMembers) {
            SysUser user1 = new SysUser();
            user1.setUserName(userMap.get(userId));
            user1.setUserId(userId);
            users.add(user1);
        }
        projectsInfo.setUserList(users);

        FileUpload fileUpload = new FileUpload();
        fileUpload.setBizType("project");
        fileUpload.setBizId(id);
        List<FileUpload> fileList = fileUploadService.selectFileUploadList(fileUpload);
        projectsInfo.setFileList(fileList);
        return projectsInfo;
    }

    private List<Long> getTeamMembersUserId(String teamMemberIds) {
        List<Long> userIds = new ArrayList<>();
        if (StringUtils.isEmpty(teamMemberIds)) {
            return userIds;
        }

        if (!teamMemberIds.contains(",")) {
            userIds.add(Long.parseLong(teamMemberIds));
            return userIds;
        }
        for (String userId : teamMemberIds.split(",")) {
            userIds.add(Long.parseLong(userId));
        }
        return userIds;
    }

    /**
     * 查询项目信息列表
     *
     * @param projects 项目信息
     * @return 项目信息
     */
    @Override
    public List<ProjectsInfo> selectProjectsList(ProjectsConditions projects) {
        List<Projects> list = projectsMapper.selectProjectsList(projects);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<Long> ownerIds = list.stream().map(Projects::getOwnerId).distinct().collect(Collectors.toList());
        Set<List<Long>> set = list.stream().map(p -> getTeamMembersUserId(p.getTeamMembers())).collect(Collectors.toSet());
        List<Long> userIds = new ArrayList<>();
        for (List<Long> ids : set) {
            userIds.addAll(ids);
        }
        userIds.addAll(ownerIds);
        userIds = userIds.stream().distinct().collect(Collectors.toList());
        List<SysUser> userList = sysUserMapper.selectUserByIds(userIds);
        Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));

        List<ProjectsInfo> projectsInfos = new ArrayList<>();
        for (Projects project : list) {
            ProjectsInfo projectsInfo = new ProjectsInfo();
            BeanUtils.copyBeanProp(projectsInfo, project);

            SysUser user = new SysUser();
            user.setUserName(userMap.get(projectsInfo.getOwnerId()));
            user.setUserId(projectsInfo.getOwnerId());
            projectsInfo.setOwner(user);

            List<Long> teamMembers = getTeamMembersUserId(project.getTeamMembers());
            List<SysUser> users = new ArrayList<>();
            for (Long userId : teamMembers) {
                SysUser user1 = new SysUser();
                user1.setUserName(userMap.get(userId));
                user1.setUserId(userId);
                users.add(user1);
            }
            projectsInfo.setUserList(users);
            projectsInfos.add(projectsInfo);
        }
        return projectsInfos;
    }

    @Override
    public Long selectProjectsCount(ProjectsConditions projects) {
        return projectsMapper.selectProjectsCount(projects);
    }

    /**
     * 新增项目信息
     *
     * @param projects 项目信息
     * @return 结果
     */
    @Override
    public int insertProjects(Projects projects) {
        projects.setCreateTime(DateUtils.getNowDate());
        projects.setUpdateTime(DateUtils.getNowDate());
        projects.setCreateBy(ShiroUtils.getLoginName());
        Long ownerId = projects.getOwnerId();
        addProjectOwnerRole(ownerId);
        return projectsMapper.insertProjects(projects);
    }

    private void addProjectOwnerRole(Long ownerId) {
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleByUserId(ownerId);
        if (CollectionUtils.isEmpty(sysUserRoles)
                || sysUserRoles.stream().noneMatch(sysUserRole -> Objects.equals(sysUserRole.getRoleId(), RuoYiConfig.getProjectOwnerRoleId()))) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(RuoYiConfig.getProjectOwnerRoleId());
            sysUserRole.setUserId(ownerId);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }

    /**
     * 修改项目信息
     *
     * @param projects 项目信息
     * @return 结果
     */
    @Override
    public int updateProjects(Projects projects) {
        projects.setUpdateTime(DateUtils.getNowDate());
        projects.setUpdateBy(ShiroUtils.getLoginName());
        Long ownerId = projects.getOwnerId();
        addProjectOwnerRole(ownerId);
        return projectsMapper.updateProjects(projects);
    }

    /**
     * 批量删除项目信息
     *
     * @param ids 需要删除的项目信息主键
     * @return 结果
     */
    @Override
    public int deleteProjectsByIds(String ids) {
        return projectsMapper.deleteProjectsByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除项目信息信息
     *
     * @param id 项目信息主键
     * @return 结果
     */
    @Override
    public int deleteProjectsById(Long id) {
        return projectsMapper.deleteProjectsById(id);
    }
}
